package com.gjintel.framework.menu.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gjintel.framework.cache.InitCacheData;
import com.gjintel.framework.cache.InitCacheData.CacheType;
import com.gjintel.framework.menu.dao.IMenuDao;
import com.gjintel.framework.menu.model.Model;
import com.gjintel.framework.menu.service.IMenuService;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.base.service.impl.BaseServiceImpl;
import com.gjintel.sdk.dto.TreeDto;
import com.gjintel.sdk.util.StringUtil;

@Service("menuService")
public class MenuServiceImpl extends BaseServiceImpl implements IMenuService {
	@Autowired
	private IMenuDao menuDao;

	@SuppressWarnings("unchecked")
	public List<String> getModelTree(List<TreeDto> treeList, String id, String nodeName, String selectIds, boolean isModelTreeDialog) {
		List<String> selIds = new ArrayList<String>();
		Map<String, List> deptTreeData = InitCacheData.getInstance().getCacheTreeData(InitCacheData.CacheType.MENU);
		if (deptTreeData != null) {
			if (!StringUtil.isEmpty(id)) {
				treeList.addAll(this.getTreePoints(deptTreeData, id));
			} else {
				if (StringUtil.isEmpty(nodeName) && StringUtil.isEmpty(selectIds)) {
					List<TreeDto> rootTreeList = this.getTreePoints(deptTreeData, InitCacheData.ROOT);
					TreeDto rootTree = null;
					if (rootTreeList != null && rootTreeList.size() == 1) {
						rootTree = rootTreeList.get(0);
						rootTree.setState("open");
						List<TreeDto> childTreeList = this.getTreePoints(deptTreeData, rootTree.getId());
						rootTree.setChildren(childTreeList);
						rootTreeList.clear();
						rootTreeList.add(rootTree);
					}
					treeList.addAll(rootTreeList);
				} else {
					// 根据查询信息，查询机构数据，并显示
					List<TreeDto> rootTreeList = this.getTreePoints(deptTreeData, InitCacheData.ROOT);
					TreeDto rootTree = null;
					if (rootTreeList != null && rootTreeList.size() == 1) {
						rootTree = rootTreeList.get(0);
						rootTree.setState("open");
						treeList.add(rootTree);
						this.getSelectMenuTree(rootTree, rootTree, nodeName, selectIds, selIds, isModelTreeDialog);
					}
				}
			}
		}
		return selIds;
	}

	/**
	 * @description 根据当前的节点逐层判断它的上级节点可是跟节点，如果不是，把该节点进行张开
	 * @author fengya
	 * @date 2015-7-30 下午04:45:13
	 * @param id
	 *            被选中的节点ID
	 * @param rootNode
	 *            根节点
	 * @return void
	 */
	private void setNodeOpen(String id, TreeDto rootNode) {
		if (id != null && !id.trim().equals(InitCacheData.ROOT)) {
			Map<String, Object> menuMap = InitCacheData.getInstance().getCacheData(CacheType.MENU);
			Object obj = menuMap.get(id);
			if (obj != null) {
				Model menu = (Model) obj;
				// 得到树中对应ID的节点
				this.getNode(rootNode, menu.getPid());
				this.setNodeOpen(menu.getPid(), rootNode);
			}
		}
	}

	/**
	 * @description 展开根节点的ID
	 * @author fengya
	 * @date 2015-7-30 下午04:46:24
	 * @param node
	 * @param pid
	 * @return void
	 */
	private void getNode(TreeDto node, String pid) {
		if (node.getId().trim().equals(pid)) {
			node.setState(TreeDto.stateValue.OPEN.toString().toLowerCase());
		} else {
			Iterator<TreeDto> nodeIt = node.getChildren().iterator();
			while (nodeIt.hasNext()) {
				this.getNode(nodeIt.next(), pid);
			}
		}
	}

	/**
	 * @description 得到节点下的菜单进行回显和查询
	 * @author fengya
	 * @date 2015-7-30 下午05:01:40
	 * @param node
	 * @param rootNode
	 * @param nodeName
	 * @param selectIds
	 * @param selIds
	 * @param isDeptTree
	 * @return void
	 */
	private void getSelectMenuTree(TreeDto node, TreeDto rootNode, String nodeName, String selectIds, List<String> selIds, boolean isDeptTree) {
		if (!StringUtil.isEmpty(selectIds)) {
			String[] selectId = selectIds.split(",");
			if (CommUtil.contains(selectId, node.getId())) {
				node.setChecked(true);
				this.setNodeOpen(node.getId(), rootNode);
			}
		}
		if (!StringUtil.isEmpty(nodeName) && node.getText().trim().contains(nodeName)) {
			// 找到查询的节点后，进行处理
			selIds.add(node.getId());
			// 遍历树，把查询后的节点对应的父节点全部展开
			this.setNodeOpen(node.getId(), rootNode);
		}
		// 遍历树的孩子节点
		List<TreeDto> childrens = this.getTreePoints(InitCacheData.getInstance().getCacheTreeData(InitCacheData.CacheType.MENU), node.getId());
		node.setChildren(childrens);
		Iterator<TreeDto> nodeIt = childrens.iterator();
		while (nodeIt.hasNext()) {
			// 递归调用孩子中的每个节点
			this.getSelectMenuTree(nodeIt.next(), rootNode, nodeName, selectIds, selIds, isDeptTree);
		}

	}

	@SuppressWarnings("unchecked")
	private List<TreeDto> getTreePoints(Map<String, List> childrenModelList, String id) {
		List<Model> childrenModel = childrenModelList.get(id);
		List<TreeDto> treeList = new ArrayList<TreeDto>();
		if (childrenModel != null && !childrenModel.isEmpty()) {
			TreeDto treeDto = null;
			Model model = null;
			Iterator<Model> modelIt = childrenModel.iterator();
			while (modelIt.hasNext()) {
				model = modelIt.next();
				treeDto = new TreeDto();
				treeDto.setIconCls("icon-menu-icon");
				treeDto.setId(model.getId());
				treeDto.setText(model.getName());
				if (InitCacheData.getInstance().getCacheTreeData(InitCacheData.CacheType.MENU).get(treeDto.getId()) != null) {
					treeDto.setChildren(new ArrayList<TreeDto>());
					treeDto.setState("closed");
				}
				treeList.add(treeDto);
			}
		}
		return treeList;
	}

	@SuppressWarnings("unchecked")
	public void findAll(Page page, Model model, Sort sort) {
		this.menuDao.findAll(page, model, sort);
		Model temp = null;
		Iterator<Model> modelIt = page.getResult().iterator();
		Model mdel = null;
		while (modelIt.hasNext()) {
			temp = modelIt.next();
			if (temp.getPid() != null) {
				mdel = ((Model) (InitCacheData.getInstance().getCacheData(InitCacheData.CacheType.MENU).get(temp.getPid())));
				if (mdel != null) {
					temp.setpName(mdel.getName());
				}
			}
		}
	}

	@Override
	public void removeData(String deleteIds) {
		Model model = null;
		for (String id : deleteIds.split(",")) {
			model = this.get(Model.class, id);
			if (model != null) {
				model.setFlag(1);
			}
		}
	}

	@Override
	public List<Model> getModelByRole(String roleId) {
		return this.menuDao.getModelByRole(roleId);
	}

	@Override
	public List<Model> findAll() {
		return this.menuDao.findAll();
	}
}
